package db

import (
	"fmt"
	"qkcoupon/errorcode"
	"qkcoupon/models"
	"reflect"
	"time"

	"doubimeizhi.com/utility"
	log "github.com/cihub/seelog"
)

/*
 *@note  使用优惠劵信息
 *@param uid: 用户ID
 *@param ccode: 优惠劵编码
 *@return uint: 错误码
 */
func SetCouponCState(uid string, mobile string, ccode string, cstate int32) uint {
	sql := "UPDATE user_coupon SET cstate=?,use_tick=?"

	if uid != "" && mobile != "" {
		sql += fmt.Sprintf(" WHERE ccode=? AND (uid='%s' or mobile='%s')", uid, mobile)
	} else if uid != "" {
		sql += fmt.Sprintf(" WHERE ccode=? AND uid='%s'", uid)
	} else {
		sql += fmt.Sprintf(" WHERE ccode=? AND mobile='%s'", mobile)
	}

	//log.Debugf("sql:%s", sql)

	_, err := qingkeMysqlHelper.Exec(sql, cstate, time.Now().Unix(), ccode)
	if err != nil {
		log.Warn(err.Error())
		return errorcode.EC_QKCOUPON_USE_COUPON_FAIL
	}

	return errorcode.EC_GL_SUCCESS
}

/*
 *@note  领取分享优惠劵
 *@param rc: PCQkCouponReceiveCoupon
 *@return uint: 错误码
 */
func ReceiveCoupon(rc *models.PCQkCouponReceiveCouponReq) (string, uint) {
	sql := "SELECT cid FROM coupon_info WHERE add_num<total_num AND cid IN (SELECT cid FROM share_cid WHERE share_id=?) ORDER BY RAND() LIMIT 1"

	//log.Debugf("sql:%s", sql)

	rows, err := qingkeMysqlHelper.Query(sql, rc.ShareId)
	if err != nil {
		log.Warn(err.Error())
		return "", errorcode.EC_GL_EXEC_SQL_FAIL
	}

	if len(rows) == 0 {
		log.Warn("len(rows) == 0")
		return "", errorcode.EC_QKCOUPON_COUPON_GRAB_END
	}

	var cid int64
	utility.SetTypeValue(rows[0]["cid"], reflect.ValueOf(&cid).Elem())

	errCode := RecountShareCouponNum(rc.ShareId, cid)
	if errCode != errorcode.EC_GL_SUCCESS {
		return "", errCode
	}

	ccode, errCode := DispatchShareCouponByMobile(rc.ShareId, cid, rc.Mobile)
	if errCode != errorcode.EC_GL_SUCCESS {
		return "", errCode
	}

	return ccode, errorcode.EC_GL_SUCCESS
}

/*
 *@note  领取推荐优惠劵
 *@param recommendId: 推荐ID
 *@param mobile: 手机号
 *@param operator: 操作者
 *@return (stirng, uint): (用户优惠劵, 错误码)
 */
func ReceiveRecommend(recommendId string, mobile string, operator models.EQKCOUPON_OPERATOR) (string, uint) {

	// 原代码采用了根据规则生成一定数量的优惠卷，在领取时随机抽取一张发放
	// 导致优惠卷的时间限制已经在创建优惠卷的时候定下来了，显然这是不对的
	// 在不重构整个新用户推荐模块的情况下，目前采用每次领取时，如果启止时间不同（目前设置为当天零点到24点）
	// 则复制一个基础优惠卷信息，并改为新的时间段

	cid, patchErr := fetchRecommendCoupon(recommendId, operator)

	if patchErr != 0 {
		return "", errorcode.EC_GL_EXEC_SQL_FAIL
	}

	var ccode string
	var errCode uint

	if operator == models.EQKCOUPON_OPERATOR_RECOMMENDER {
		ccode, errCode = DispatchRecommendToRecommenderByMobile(recommendId, cid, mobile)
	} else {
		ccode, errCode = DispatchRecommendToReceiveByMobile(recommendId, cid, mobile)
	}

	if errCode != errorcode.EC_GL_SUCCESS {
		return "", errCode
	}

	return ccode, errorcode.EC_GL_SUCCESS
}

func fetchRecommendCoupon(recommendId string, operator models.EQKCOUPON_OPERATOR) (int64, uint) {

	// 随机抽取改为选择最新的一张

	sql := "SELECT cid,start_tick,ctype,utype,lmode,sum,discount FROM coupon_info WHERE cid IN (SELECT cid FROM recommend_cid WHERE recommend_id=? AND operator=?) ORDER BY cid DESC LIMIT 1"
	rows, err := qingkeMysqlHelper.Query(sql, recommendId, operator)
	if err != nil {
		log.Warn(err.Error())
		return 0, errorcode.EC_GL_EXEC_SQL_FAIL
	}

	if len(rows) == 0 {
		log.Warn("len(rows) == 0")
		return 0, errorcode.EC_QKCOUPON_COUPON_GRAB_END
	}

	var cid int64
	utility.SetTypeValue(rows[0]["cid"], reflect.ValueOf(&cid).Elem())

	loc, _ := time.LoadLocation("Local")
	timeFormat := "2006.01.02"
	startTime := time.Now().Format(timeFormat)
	endTime := time.Now().Add(time.Hour * 24 * 7).Format(timeFormat)
	startTick, _ := time.ParseInLocation(timeFormat, startTime, loc)
	endTick, _ := time.ParseInLocation(timeFormat, endTime, loc)
	endTick = endTick.Add(-time.Second)

	log.Debugf("start_tick：%d", rows[0]["start_tick"].(int64))
	log.Debugf("old cid：%d", cid)

	if rows[0]["start_tick"].(int64) == startTick.Unix() {
		log.Debugf("使用现有CID：%d", cid)
		return cid, errorcode.EC_GL_SUCCESS
	}

	//timeRangeString := fmt.Sprintf(`{"date":[{"start":"%s","end":"%s"}],"time":[{"start":"08:00","end":"11:00"}]}`, startTime, endTime)
	//timeRange := &models.PCQkCouponTimeRanges{}
	//json.Unmarshal([]byte(timeRangeString), timeRange)

	req := &models.PSQkCouponCreateCouponReq{}
	//req.TimeRanges = timeRange
	utility.SetTypeValue(rows[0]["ctype"], reflect.ValueOf(&req.Ctype).Elem())
	utility.SetTypeValue(rows[0]["lmode"], reflect.ValueOf(&req.Lmode).Elem())
	utility.SetTypeValue(rows[0]["utype"], reflect.ValueOf(&req.Utype).Elem())
	utility.SetTypeValue(rows[0]["sum"], reflect.ValueOf(&req.Sum).Elem())
	utility.SetTypeValue(rows[0]["discount"], reflect.ValueOf(&req.Discount).Elem())

	newCid, errc := CreateCoupon(req, startTick.Unix(), endTick.Unix(), 0)
	if errc != 0 {
		return 0, errorcode.EC_GL_EXEC_SQL_FAIL
	}

	sql2 := "UPDATE recommend_cid SET cid=? WHERE recommend_id=? AND operator=? ORDER BY cid DESC LIMIT 1"
	numUpdate, updateErr := qingkeMysqlHelper.Exec(sql2, newCid, recommendId, operator)
	if updateErr != nil {
		return 0, errorcode.EC_GL_EXEC_SQL_FAIL
	}
	if numUpdate == 0 {
		return 0, errorcode.EC_GL_EXEC_SQL_FAIL
	}

	log.Debugf("更新CID：%d", newCid)
	return newCid, errorcode.EC_GL_SUCCESS
}

func UpdateRecommendRecommendId(recommendId string, mobile string) (string, uint) {
	// sql := "SELECT cid FROM coupon_info WHERE cid IN (SELECT cid FROM recommend_cid WHERE recommend_id=? AND operator=?) ORDER BY cid DESC LIMIT 1"
	// rows, err := qingkeMysqlHelper.Query(sql, recommendId, models.EQKCOUPON_OPERATOR_RECOMMENDER)
	// if err != nil {
	// 	log.Warn(err.Error())
	// 	return "", errorcode.EC_GL_EXEC_SQL_FAIL
	// }

	// if len(rows) == 0 {
	// 	log.Warn("len(rows) == 0")
	// 	return "", errorcode.EC_QKCOUPON_COUPON_GRAB_END
	// }

	// var cid int64
	// utility.SetTypeValue(rows[0]["cid"], reflect.ValueOf(&cid).Elem())

	cid, cidErr := fetchRecommendCoupon(recommendId, models.EQKCOUPON_OPERATOR_RECOMMENDER)
	if cidErr != 0 {
		return "", cidErr
	}

	sql := "SELECT ccode FROM receive_recommend WHERE receiver=?"
	rows, err := qingkeMysqlHelper.Query(sql, mobile)
	if err != nil {
		log.Warn(err.Error())
		return "", errorcode.EC_GL_EXEC_SQL_FAIL
	}

	if len(rows) == 0 {
		log.Warn("len(rows) == 0")
		return "", errorcode.EC_QKCOUPON_RECOMMEND_NOT_EXIST
	}

	var ccode string
	utility.SetTypeValue(rows[0]["ccode"], reflect.ValueOf(&ccode).Elem())

	sql = "UPDATE receive_recommend SET recommend_id=?,cid=? WHERE ccode=?"
	_, err = qingkeMysqlHelper.Exec(sql, recommendId, cid, ccode)
	if err != nil {
		log.Warn(err.Error())
		return "", errorcode.EC_GL_EXEC_SQL_FAIL
	}

	sql = "UPDATE user_coupon SET cid=?,mobile=? WHERE ccode=?"
	_, err = qingkeMysqlHelper.Exec(sql, cid, mobile, ccode)
	if err != nil {
		log.Warn(err.Error())
		return "", errorcode.EC_GL_EXEC_SQL_FAIL
	}

	return "", errorcode.EC_GL_SUCCESS
}
